package base.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author : GuoFei
 * @date : 2018/11/5 11:44
 */
@Controller
@RequestMapping("wx")
public class WxController {

    @RequestMapping("state")
    @ResponseBody
    public void state(HttpServletResponse response) {
        try {
            System.out.println("begin---");
            response.setContentType("image/jpg");
            ServletOutputStream sos = response.getOutputStream();
            // 禁止页面缓存
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            // 创建内存图象并获得其图形上下文
            Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
            BufferedImage screenshot = (new Robot())
                    .createScreenCapture(new Rectangle(0, 0, (int) dimension
                            .getWidth(), (int) dimension.getHeight()));
            // 将图像输出到客户端
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ImageIO.write(screenshot, "jpg", bos);
            byte[] buf = bos.toByteArray();
            response.setContentLength(buf.length);
            sos.write(buf);
            bos.close();
            sos.close();
        } catch (Exception e) {
            return;
        }
    }

    @RequestMapping("start")
    @ResponseBody
    public JSONObject start(HttpServletResponse response) {
        try {
            runbat("C:\\Users\\mayn\\Desktop\\start.bat");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JSONObject();
    }

    @RequestMapping("exit")
    @ResponseBody
    public JSONObject exit() {
        runbat("C:\\Users\\mayn\\Desktop\\stop.bat");
        runbat("C:\\Users\\mayn\\Desktop\\clean.bat");
        return new JSONObject();
    }



    public void runbat(String batName) {
        Runtime rt = Runtime.getRuntime();
        Process ps = null;
        try {
            ps = rt.exec("cmd.exe /C start /b " + batName);
            ps.waitFor();
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        int i = ps.exitValue();
        if (i == 0) {
            System.out.println("执行完成.");
        } else {
            System.out.println("执行失败.");
        }
    }

}
